# 根据不同的按键绘制不同的图形
# 按l 画线
# 按c 画圆
# 按r 画矩形
import cv2
import numpy as np

# 图形类型
cur_shape = 0,
# 起始位置
start_pos = (0, 0)
# 创建背景图
img = np.zeros((480, 640, 3), np.uint8)


# 鼠标事件监听回调函数
def callback(event, x, y, flags, userdata):
    global cur_shape, start_pos
    # 左键按下，记录起始位置
    if event == cv2.EVENT_LBUTTONDOWN:
        start_pos = (x, y)
    # 左键抬起，绘制图形
    elif event == cv2.EVENT_LBUTTONUP:
        if cur_shape == 0:
            # 画直线
            cv2.line(img, start_pos, (x, y), (0, 0, 255), 3)
        elif cur_shape == 1:
            # 画矩形
            cv2.rectangle(img, start_pos, (x, y), (0, 0, 255), 3)
        elif cur_shape == 2:
            # 画圆形
            a = x - start_pos[0]
            b = y - start_pos[1]
            r = int((a ** 2 + b ** 2) ** 0.5)
            cv2.circle(img, start_pos, r, (0, 0, 255), 3)
        else:
            print(' 暂不支持的操作')


cv2.namedWindow('drawTool', cv2.WINDOW_NORMAL)
cv2.setMouseCallback('drawTool', callback)
while True:
    cv2.imshow('drawTool', img)
    key = cv2.waitKey(1)
    if key == ord('q'):
        break
    elif key == ord('l'):
        cur_shape = 0
    elif key == ord('r'):
        cur_shape = 1
    elif key == ord('c'):
        cur_shape = 2

cv2.destroyAllWindows()
